package com.smart.community.common.base.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 分页底层工具类
 * @author 子未语
 */
public class CommonBeanutils extends BeanUtils {
    public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) {
        if (ObjectUtils.isEmpty(source) || ObjectUtils.isEmpty(targetSupplier)) {
            return null;
        }
        T t = targetSupplier.get();
        copyProperties(source, t);
        return t;
    }

    /**
     * lambda表达式的方式
     */
    public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
        if (null == sources || null == targetSupplier) {
            return null;
        }
        return sources.stream().map(s -> convertTo(s, targetSupplier)).collect(Collectors.toList());
    }

    public static <S, T> IPage<T> convertPage(IPage<S> source, Supplier<T> targetSupplier) {
        if (source == null || targetSupplier == null) {
            return null;
        }
        // 创建新的分页对象
        IPage<T> target = new Page<>(source.getCurrent(), source.getSize(), source.getTotal());
        // 转换列表项
        List<T> convertedList = convertListTo(source.getRecords(), targetSupplier);
        // 设置转换后的列表
        target.setRecords(convertedList);
        return target;
    }
}
